package com.code.generator.builder;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.code.generator.ExceputionUtils;
import com.code.generator.GeneratorUtils;
import com.code.generator.entity.TableEntity;
import com.code.view.entity.HandlerVO;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;


/**
 * 创建Common类
 *
 *
 * @author 朱国军
 * @version 2015年2月26日 朱国军
 */
public class CommonBuilder extends BaseBuilder {

    private void createCommon(Configuration cfg, Map<String, Object> tableData, String className, String packageNmae, String ftlName,
            String outPutPath,String packagePath) throws IOException, TemplateException {
        /* 获取或创建一个模版 */
        Template temp = cfg.getTemplate(ftlName, "UTF-8");
        String filePath = outPutPath + GeneratorUtils.getFilePath(packagePath) +  packageNmae + "/" + className + ".java";
        GeneratorUtils.witeFile(filePath, temp, tableData);
    }


    @Override
    protected Map<String, Object> getDataMap(TableEntity tableEntity, String packagePath, HandlerVO handlerVO) {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("commonPackage", handlerVO.getCommonPackage());
        dataMap.put("author", handlerVO.getAuthor());
        dataMap.put("currentDate", GeneratorUtils.getCurrentDate());
        return dataMap;
    }


    @Override
    public boolean builder(TableEntity tableEntity, String packagePath, HandlerVO handlerVO, Configuration cfg) {
        Map<String, Object> dataMap = getDataMap(null, null, handlerVO);
        String outPutPath = handlerVO.getOutPutPath();
        try {
            createCommon(cfg, dataMap, "BaseParam", "common", "BaseParam.ftl", outPutPath,packagePath);
            if(handlerVO.getMyBatis().getSelection()){
                createCommon(cfg, dataMap, "BaseDao", "common", "BaseDao_mybatis.ftl", outPutPath,packagePath);
            }else{
                createCommon(cfg, dataMap, "BaseDao", "common", "BaseDao_ibatis.ftl", outPutPath,packagePath);
                createCommon(cfg, dataMap, "DynamicSqlSessionDaoSupport", "common", "DynamicSqlSessionDaoSupport.ftl", outPutPath,packagePath);
            }
        } catch (IOException e) {
            ExceputionUtils.logging("生成common包时IO异常", e);
            return false;
        } catch (TemplateException e) {
            ExceputionUtils.logging("生成common包时模版异常", e);
            return false;
        } catch (Exception e) {
            ExceputionUtils.logging("生成common包时其他异常", e);
            return false;
        }
        return true;
    }
}
